<template>
    <a-modal
        title="批量添加监控变量"
        :visible="visible"
        :width="450"
        :confirm-loading="loading"
        @ok="handleOk"
        @cancel="handleCancel"
    >
        <a-form-model
            ref="form"
            :model="formData"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            class="compact-form"
        >
            <a-form-model-item label="变量个数" class="inline-form-item">
                <a-input v-model="formData.variableIndex" placeholder="变量个数" />
            </a-form-model-item>

            <a-form-model-item label="名称" class="inline-form-item">
                <a-input v-model="formData.variableName" placeholder="变量名称" />
            </a-form-model-item>

            <a-form-model-item label="别名" class="inline-form-item">
                <a-input v-model="formData.variableAlias" placeholder="变量别名" />
            </a-form-model-item>

            <a-form-model-item label="数据类型" class="inline-form-item">
                <a-select v-model="formData.dataType" style="width: 100%;">
                    <a-select-option v-for="item in dataTypeOptions" :key="item" :value="item">{{ item }}</a-select-option>
                </a-select>
            </a-form-model-item>

            <a-form-model-item label="小数位" class="inline-form-item">
                <a-input v-model="formData.bitOffset" placeholder="小数位" />
            </a-form-model-item>

            <a-form-model-item label="单位" class="inline-form-item">
                <a-input v-model="formData.unit" placeholder="单位" />
            </a-form-model-item>

            <a-form-model-item label="量程转换系数" class="inline-form-item">
                <a-input v-model="formData.conversionFactor" placeholder="量程转换系数" />
            </a-form-model-item>

            <a-form-model-item label="地址" class="inline-form-item">
                <div class="address-field">
                    <a-input v-model="formData.address" placeholder="地址" />
                    <a-checkbox v-model="formData.isHex" @change="handleHexChange">十六进制</a-checkbox>
                </div>
            </a-form-model-item>

            <a-form-model-item label="地址递增单位" class="inline-form-item">
                <a-input v-model="formData.addressUnit" placeholder="地址递增单位" />
            </a-form-model-item>

            <a-form-model-item label="类型" class="inline-form-item">
                <a-select v-model="formData.registerType" style="width: 100%;">
                    <a-select-option v-for="item in typeOptions" :key="item" :value="item">{{ item }}</a-select-option>
                </a-select>
            </a-form-model-item>
        </a-form-model>
    </a-modal>
</template>

<script>
import tabManager from '@/api/tab-manager'

export default {
    name: 'BatchVariablesModal',
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        portProtoType: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            loading: false,
            formData: {
                variableIndex: '1',
                variableName: '',
                variableAlias: '',
                dataType: 'bool',
                bitOffset: '1',
                unit: 'int',
                conversionFactor: '1',
                address: '',
                isHex: false,
                addressUnit: '1',
                registerType: '',
                addressNum: 0 // 整形
            },
            dataTypeOptions: [
                'bool',
                'int',
                'float',
                'double',
                'string',
                'uint16',
                'int16',
                'uint32',
                'int32',
                'uint64',
                'int64'
            ],
            typeOptions: []
        }
    },
    watch: {
        visible(val) {
            if (val) {
                this.loadTypeOptions()
            }
        }
    },
    methods: {
        resetForm() {
            this.formData = {
                variableIndex: '1',
                variableName: '',
                dataType: 'bool',
                bitOffset: '1',
                unit: 'int',
                conversionFactor: '1',
                address: '',
                isHex: false,
                addressUnit: '1',
                registerType: '',
                addressNum: 0, // 整形
                variableIndexNum: 0
            }
        },

        async loadTypeOptions() {
            try {
                console.log('🔍 [BatchVariablesModal] 加载类型选项', this.portProtoType)
                const response = await tabManager.monitor.getVarRegistersTypeOptions(
                    this.portProtoType
                )
                if (response && response.code === 0) {
                    let rawOptions = JSON.parse(response.data)
                    
                    // 过滤重复数据 - 确保数组元素唯一性
                    if (Array.isArray(rawOptions)) {
                        this.typeOptions = [...new Set(rawOptions)]
                        console.log(
                            '🧹 [BatchVariablesModal] 已过滤重复数据',
                            { 原始数量: rawOptions.length, 去重后数量: this.typeOptions.length }
                        )
                    } else {
                        this.typeOptions = rawOptions || []
                    }
                    
                    if (this.typeOptions.length > 0) {
                        this.formData.registerType = this.typeOptions[0]
                    }
                }                
            } catch (error) {
                console.error('❌ [BatchVariablesModal] 加载类型选项失败:', error)
                this.$message.error('加载数据类型选项失败')
            }
        },

        validateForm() {
            if (!this.formData.variableIndex) {
                this.$message.error('变量序号不能为空')
                return false
            }
            if (!this.formData.variableName) {
                this.$message.error('变量名称不能为空')
                return false
            }
            if (!this.formData.address) {
                this.$message.error('地址不能为空')
                return false
            }
            return true
        },
        handleHexChange() {
            const address = this.formData.address
            if (!address) {
                console.log('⚠️ [VariablePropertiesModal] 地址为空，跳过转换')
                return
            }

            try {
                if (this.formData.isHex) {
                    // 十进制转十六进制
                    const decimal = parseInt(address, 10)
                    if (isNaN(decimal)) {
                        throw new Error('无效的十进制数值')
                    }
                    this.formData.address = '0x' + decimal.toString(16).toUpperCase()
                } else {
                    // 十六进制转十进制
                    const decimal = parseInt(address, 16)
                    if (isNaN(decimal)) {
                        throw new Error('无效的十六进制数值')
                    }
                    this.formData.address = decimal.toString(10)
                }
                console.log('✅ [VariablePropertiesModal] 地址转换成功:', this.formData.address)
            } catch (error) {
                console.error('❌ [VariablePropertiesModal] 地址转换失败:', error)
                this.$message.error('地址转换失败，请检查格式')
                // 发生错误时保持原值不变
                this.formData.address = address
            }
        },        
        async handleOk() {
            if (!this.validateForm()) {
                return
            }
            
            this.loading = true
            try {
                // 转换数据格式以匹配API要求
                const formattedData = this.formData
                // 地址转换为整形，需要判断是否是十六进制
                if (formattedData.isHex) {
                    formattedData.addressNum = parseInt(formattedData.address, 16)
                } else {
                    formattedData.addressNum = parseInt(formattedData.address)
                }
                this.$emit('ok', formattedData)
            } finally {
                this.loading = false
            }
        },
        
        handleCancel() {
            this.resetForm()
            this.$emit('cancel')
        }
    }
}
</script>

<style scoped>
.compact-form {
    padding: 8px 0;
}
.inline-form-item {
    margin-bottom: 8px;
}
.inline-form-item :deep(.ant-form-item-label) {
    padding: 0 8px 0 0;
    line-height: 32px;
    white-space: nowrap;
    text-align: left;
}
.inline-form-item :deep(.ant-form-item-label > label) {
    color: #606266;
    height: 32px;
    line-height: 32px;
}
.inline-form-item :deep(.ant-form-item-label > label::after) {
    content: "";
    margin: 0;
}
.inline-form-item :deep(.ant-form-item-control) {
    line-height: 32px;
}
.address-field {
    display: flex;
    align-items: center;
    gap: 8px;
}
.address-field .ant-input {
    flex: 1;
}
</style> 